package com.zb.controller.settings;

import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.zb.common.annotation.Permission;
import com.zb.common.annotation.WriteLog;
import com.zb.common.exception.BusinessException;
import com.zb.common.po.enums.ResponseCode;
import com.zb.common.po.enums.RoleStatus;
import com.zb.common.po.enums.UserStatus;
import com.zb.common.po.model.Role;
import com.zb.common.po.model.SessionUser;
import com.zb.common.po.model.User;
import com.zb.common.po.query.RoleQuery;
import com.zb.common.po.query.UserQuery;
import com.zb.common.po.vo.AjaxResponse;
import com.zb.common.utils.PaginationResult;
import com.zb.common.utils.SessionUserUtil;
import com.zb.controller.IndexController;
import com.zb.service.RoleService;
import com.zb.service.UserService;

@Controller
@RequestMapping(value = "/settings")
public class UserSettingsController {

    Logger logger = LoggerFactory.getLogger(IndexController.class);

    @Resource
    private UserService userService;

    @Resource
    private RoleService roleService;

    @Permission(code = "user:list")
    @RequestMapping(value = "/user_list.do")
    public String userList() {
        return "page/settings/user_list";
    }

    @Permission(code = "user:list")
    @ResponseBody
    @RequestMapping(value = "/loadUserList.do")
    public AjaxResponse<PaginationResult<User>> loadUserList(UserQuery query) {
        AjaxResponse<PaginationResult<User>> response = new AjaxResponse<PaginationResult<User>>();
        try {
            PaginationResult<User> result = userService.findUsersByPage(query);
            response.setData(result);
            response.setResponseCode(ResponseCode.SUCCESS);
        } catch (Exception e) {
            logger.error("查询用户失败：{}", e);
            response.setResponseCode(ResponseCode.SERVERERROR);
            response.setErrorMsg("查询用户失败");
        }
        return response;
    }

    @RequestMapping(value = "/user_2SaveUser.do")
    public ModelAndView user_2SaveUser(UserQuery query) {
        ModelAndView result = new ModelAndView();
        try {
            if (!StringUtils.isEmpty(query.getUserId())) {
                User user = userService.findUserByUserId(query.getUserId());
                result.addObject("user", user);
            }
            RoleQuery roleQuery = new RoleQuery();
            roleQuery.setStatus(RoleStatus.NORMAL);
            List<Role> roleList = roleService.findAllRoles(roleQuery);
            result.addObject("roleList", roleList);
            result.setViewName("page/settings/user_edit");
            return result;
        } catch (Exception e) {
            logger.error("获取用户，角色异常：{}", e);
            return result;
        }
    }

    @Permission(code = "user:add")
    @ResponseBody
    @RequestMapping(value = "/user_add.do")
    @WriteLog(opObject = "操作人员", opDescription = "新增操作人员：#{#param0}", paramIndexes = { 0 })
    public AjaxResponse<?> user_add(User user) {
        AjaxResponse<?> response = new AjaxResponse<Object>();
        try {
            userService.saveUser(user);
            response.setResponseCode(ResponseCode.SUCCESS);
        } catch (BusinessException e) {
            logger.error("保存用户失败：{}", e);
            response.setResponseCode(ResponseCode.BUSINESSERROR);
            response.setErrorMsg(e.getMessage());
        } catch (Exception e) {
            logger.error("保存用户失败：{}", e);
            response.setResponseCode(ResponseCode.BUSINESSERROR);
            response.setErrorMsg("保存用户失败");
        }
        return response;
    }

    @Permission(code = "user:update")
    @ResponseBody
    @RequestMapping(value = "/user_update.do")
    @WriteLog(opObject = "操作人员", opDescription = "修改操作人员：#{#param0}", paramIndexes = { 0 })
    public AjaxResponse<?> user_update(User user) {
        AjaxResponse<?> response = new AjaxResponse<Object>();
        try {
            userService.saveUser(user);
            response.setResponseCode(ResponseCode.SUCCESS);
        } catch (BusinessException e) {
            logger.error("保存用户失败：{}", e);
            response.setResponseCode(ResponseCode.BUSINESSERROR);
            response.setErrorMsg(e.getMessage());
        } catch (Exception e) {
            logger.error("保存用户失败：{}", e);
            response.setResponseCode(ResponseCode.BUSINESSERROR);
            response.setErrorMsg("保存用户失败");
        }
        return response;
    }

    @Permission(code = "user:op")
    @ResponseBody
    @RequestMapping(value = "/user_disable.do")
    @WriteLog(opObject = "禁用操作人员", opDescription = "禁用操作人员：#{#param0}", paramIndexes = { 0 })
    public AjaxResponse<?> user_disable(Integer[] userIds) {
        AjaxResponse<?> response = new AjaxResponse<Object>();
        try {
            userService.updateUserStatus(userIds, UserStatus.DISABLE);
            response.setResponseCode(ResponseCode.SUCCESS);
        } catch (BusinessException e) {
            logger.error("禁用操作人员失败：{}", e);
            response.setResponseCode(ResponseCode.BUSINESSERROR);
            response.setErrorMsg(e.getMessage());
        } catch (Exception e) {
            logger.error("禁用操作人员失败：{}", e);
            response.setResponseCode(ResponseCode.BUSINESSERROR);
            response.setErrorMsg("禁用操作人员失败");
        }
        return response;
    }

    @Permission(code = "user:op")
    @ResponseBody
    @RequestMapping(value = "/user_enable.do")
    @WriteLog(opObject = "启用操作人员", opDescription = "启用操作人员：#{#param0}", paramIndexes = { 0 })
    public AjaxResponse<?> user_enable(Integer[] userIds) {
        AjaxResponse<?> response = new AjaxResponse<Object>();
        try {
            userService.updateUserStatus(userIds, UserStatus.NORMAL);
            response.setResponseCode(ResponseCode.SUCCESS);
        } catch (BusinessException e) {
            logger.error("启用操作人员失败：{}", e);
            response.setResponseCode(ResponseCode.BUSINESSERROR);
            response.setErrorMsg(e.getMessage());
        } catch (Exception e) {
            logger.error("启用操作人员失败：{}", e);
            response.setResponseCode(ResponseCode.BUSINESSERROR);
            response.setErrorMsg("启用操作人员失败");
        }
        return response;
    }

    @Permission(code = "user:op")
    @ResponseBody
    @RequestMapping(value = "/user_delete.do")
    @WriteLog(opObject = "删除操作人员", opDescription = "删除操作人员：#{#param0}", paramIndexes = { 0 })
    public AjaxResponse<?> user_delete(Integer[] userIds) {
        AjaxResponse<?> response = new AjaxResponse<Object>();
        try {
            userService.delteUser(userIds);
            response.setResponseCode(ResponseCode.SUCCESS);
        } catch (BusinessException e) {
            logger.error("删除操作人员：{}", e);
            response.setResponseCode(ResponseCode.BUSINESSERROR);
            response.setErrorMsg(e.getMessage());
        } catch (Exception e) {
            logger.error("删除操作人员：{}", e);
            response.setResponseCode(ResponseCode.BUSINESSERROR);
            response.setErrorMsg("删除操作人员失败");
        }
        return response;
    }

    @RequestMapping(value = "/user_settings.do")
    public ModelAndView user_settings(HttpSession session) {
        ModelAndView view = new ModelAndView("page/settings/user_settings");
        SessionUser sessionUser = SessionUserUtil.getSessionUser(session);
        try {
            User user = userService.findUserByUserId(sessionUser.getUserId());
            view.addObject("user", user);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return view;
    }

    @ResponseBody
    @RequestMapping(value = "/user_update_self.do")
    public AjaxResponse<?> user_update_self(String oldPwd, User user,
            HttpSession session) {
        AjaxResponse<?> response = new AjaxResponse<Object>();
        try {
            user.setUserId(SessionUserUtil.getSessionUser(session).getUserId());
            userService.updateUserSelf(oldPwd, user);
            response.setResponseCode(ResponseCode.SUCCESS);
        } catch (BusinessException e) {
            logger.error("保存用户失败：{}", e);
            response.setResponseCode(ResponseCode.BUSINESSERROR);
            response.setErrorMsg(e.getMessage());
        } catch (Exception e) {
            logger.error("保存用户失败：{}", e);
            response.setResponseCode(ResponseCode.BUSINESSERROR);
            response.setErrorMsg("保存用户失败");
        }
        return response;
    }
}
